package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.context.Config;
import cn.livingCloud.entity.core.CaseImage;
import cn.livingCloud.entity.system.ImageResource;
import cn.livingCloud.entity.system.Setting;
import cn.livingCloud.repository.CaseImageMapper;
import cn.livingCloud.repository.ImageResourceMapper;
import cn.livingCloud.repository.SettingMapper;
import cn.livingCloud.utils.UuidGenerator;
import cn.livingCloud.wechat.handler.WxImageDownloadHandler;
import org.apache.commons.io.FilenameUtils;

import java.io.File;

/**
 * Created by 唐旭 on 2016/6/27.
 */
public class CaseImageDownloadHandler {
    protected transient SettingMapper settingMapper = BeanProvider.getBean(SettingMapper.class);
    protected transient CaseImageMapper imageMapper = BeanProvider.getBean(CaseImageMapper.class);
    protected transient ImageResourceMapper imageResourceMapper = BeanProvider.getBean(ImageResourceMapper.class);

    private CaseImage caseImage;

    public CaseImageDownloadHandler(CaseImage image) {
        this.caseImage = image;
    }

    public void handler() {
        if (caseImage.getUrl().startsWith("wxImage:")) {
            downloadImageToServer();
        }
    }

    private void downloadImageToServer() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Setting setting = settingMapper.findSetting();
                if (setting == null) {
                    return;
                }
                String url = caseImage.getUrl();
                String[] split = url.split(":");
                if (split.length != 2) {
                    return;
                }

                String generate = UuidGenerator.generate();
                File file = new File(Config.UPLOAD_IMAGE_PATH, generate);

                WxImageDownloadHandler handler = new WxImageDownloadHandler(setting.getAppid(), split[1], file, setting.getSecret());
                String fileName = handler.downloadImage();
                createAndUpdateCaseImage(generate, fileName);
            }

            private void createAndUpdateCaseImage(String generate, String fileName) {
                ImageResource resource = new ImageResource();
                resource.setPath(generate);
                resource.setOriginalFileName(fileName);
                resource.setExtName(FilenameUtils.getExtension(fileName));
                imageResourceMapper.save(resource);
                caseImage.setUrl(resource.getUrl());
                imageMapper.updateByPrimaryKey(caseImage);
            }
        }).start();
    }
}
